package com.vhukze.basics.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配置null转"" null转[]
 *
 * @author vhukze
 * @date 2022/5/30 15:56
 */
@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 空字符串
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                String fieldName = jsonGenerator.getOutputContext().getCurrentName();
                try {
                    //反射获取字段类型
                    Class<?> aClass = jsonGenerator.getCurrentValue().getClass();

                    List<String> fields = Arrays.stream(aClass.getDeclaredFields())
                            .map(Field::getName).collect(Collectors.toList());

                    Field field;

                    // 如果是map
                    if (Map.class.isAssignableFrom(aClass)) {

                        if (Arrays.stream(aClass.getDeclaredFields()).anyMatch(f -> f.getName().equals(fieldName))) {
                            field = aClass.getDeclaredField(fieldName);
                        } else {
                            //字符串型空值""
                            jsonGenerator.writeString("");
                            return;
                        }
                    } else {
                        if (fields.contains(fieldName)){
                            field = aClass.getDeclaredField(fieldName);
                        }else{
                            field = aClass.getSuperclass().getDeclaredField(fieldName);
                        }
                    }

                    field.setAccessible(true);
                    if (String.class.isAssignableFrom(field.getType())) {
                        //字符串型空值""
                        jsonGenerator.writeString("");
                        return;
                    } else if (Collection.class.isAssignableFrom(field.getType())) {
                        //列表型空值返回[]
                        jsonGenerator.writeStartArray();
                        jsonGenerator.writeEndArray();
                        return;
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }

                // 不处理默认情况会报错
                jsonGenerator.writeNull();
            }
        });
        return objectMapper;
    }
}